-module(example1).
-export([test_erlsom/1]).

%% example1.hrl contains the record definitions.
%% It was generated using erlsom:writeHrl
-include("example1.hrl").

test_erlsom(Test) ->
  XsdFile = "example1.xsd",
  {ok, Model} = erlsom:compile_file(XsdFile),
  Xml = "example1.xml",
  {ok, TestSuite} = erlsom:parse_file(Xml, Model),
  Cases = TestSuite#testConfig.'case',
  Dir = TestSuite#testConfig.path,
  case findCase(Cases, Test) of
    {ok, Case} -> execute_case(Case, Dir);
    _Else -> io:format("Case not found\n", [])
  end.

execute_case(#'case'{name=Name, xsd=XSD, xml=XML}, Path) ->
  io:format("example: ~p\n", [Name]),
  XsdFile = filename:join([Path, XSD]),
  io:format("compiling xsd ~p...\n", [XsdFile]),
  Result = erlsom:compile_file(XsdFile, []),
  case Result of
    {error, Message} ->
      io:format("XSD error: ~p\n", [Message]);
    {ok, Model} ->
      Xml = filename:join([Path, XML]),
      erlsom:parse_file(Xml, Model)
  end.

findCase([], _Name) ->
  false;
findCase([Case = #'case'{name=Name}| _], Name) ->
  {ok, Case};
findCase([_| Tail], Name) ->
  findCase(Tail, Name).
